package com.jy.oms.framework.asyn.task.web;

import com.alibaba.fastjson.JSON;
import com.jy.oms.framework.asyn.task.constants.CacheConstants;
import com.jy.oms.framework.asyn.task.core.RedissonClientProxy;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author liuquan
 */
@WebServlet("/taskQueue/server/list")
public class ExecutorServerServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        RedissonClient redissonClient = RedissonClientProxy.getRedissonClient();
        String cacheKey = CacheConstants.genFrameworkKey(CacheConstants.EXECUTOR_SERVER_REGIST);
        RMap<String, String> rMap = redissonClient.getMap(cacheKey);
        Map<String, String> resultMap = rMap.readAllMap();
        List<ExecutorServerVo> executorServerVoList = resultMap.entrySet().stream()
                .map(entry -> new ExecutorServerVo().setBusinessGroup(entry.getKey()).setServer(entry.getValue()))
                .collect(Collectors.toList());
        print(request, response, TaskQueueResponse.success(executorServerVoList));
    }

    private void print(HttpServletRequest request, HttpServletResponse response, Object msg) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        PrintWriter writer = response.getWriter();
        writer.write(JSON.toJSONString(msg));
        writer.flush();
        writer.close();
    }
}
